package org.truenewx.tnxjee.core.crypto;

import java.util.Base64;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.encrypt.AesBytesEncryptor;
import org.truenewx.tnxjee.core.util.EncryptUtil;
import org.truenewx.tnxjee.core.util.StringUtil;

/**
 * AES字符串加密器。与通用AES加密器不同的是，本类仅密码固定，盐值并不固定，且加密后的密文为字符串
 */
public class AesStringEncryptor implements KeyBidirectionalEncryptor {

    private final String password;

    public AesStringEncryptor(String password) {
        this.password = password;
    }

    /**
     * 加密
     *
     * @param source 任意形式的原文
     * @param key    密钥，必须为16位及以下的数字或16进制字符串
     * @return 加密后的密文
     */
    @Override
    public String encrypt(Object source, Object key) {
        if (source == null) {
            return null;
        }
        String salt = getSalt(key);
        AesBytesEncryptor encryptor = new AesBytesEncryptor(this.password, salt);
        byte[] encryptedBytes = encryptor.encrypt(EncryptUtil.toBytes(source));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    private String getSalt(Object key) {
        String s = key.toString();
        if (s.length() > 16 || !StringUtil.isHex(s)) {
            return EncryptUtil.encryptByMd5_16(s);
        }
        return StringUtils.leftPad(s, 16, "0");
    }

    /**
     * 解密
     *
     * @param encryptedText 密文
     * @param key           密钥，必须为16位及以下的数字或16进制字符串
     * @return 解密后的明文
     */
    @Override
    public String decrypt(String encryptedText, Object key) {
        if (encryptedText == null) {
            return null;
        }
        String salt = getSalt(key);
        AesBytesEncryptor encryptor = new AesBytesEncryptor(this.password, salt);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = encryptor.decrypt(encryptedBytes);
        return new String(decryptedBytes);
    }

}
